/*
 * Copyright (C) 2012 ZXing authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mylhyl.zxing.scanner.camera.open;

import ohos.agp.graphics.SurfaceOps;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.media.camera.CameraKit;
import ohos.media.camera.device.Camera;
import ohos.media.camera.device.CameraInfo;
import ohos.media.camera.device.CameraStateCallback;


@SuppressWarnings("deprecation")
public final class OpenCameraInterface {

    private static final String TAG = OpenCameraInterface.class.getName();

    public static final int NO_REQUESTED_CAMERA = -1;

    private OpenCameraInterface() {
    }

    public static OpenCamera open(Context context, int cameraId, SurfaceOps surfaceOps) {

        //CameraKit类是相机的入口API类，用于获取相机设备特性、打开相机
        CameraKit cameraKit = CameraKit.getInstance(context);
        if (cameraKit == null) {
            return null;
        }
        // 获取当前设备的逻辑相机列表
        String[] cameraIds = cameraKit.getCameraIds();

        if (cameraIds.length == 0) {
            return null;
        }
        if (cameraId >= cameraIds.length) {
            return null;
        }

        if (cameraId <= NO_REQUESTED_CAMERA) {
            cameraId = 0;

            while (cameraId < cameraIds.length) {

                //获取指定逻辑相机的信息
                CameraInfo cameraInfo = cameraKit.getCameraInfo(cameraIds[0]);

                if (CameraFacing.values()[cameraInfo.getFacingType()] == CameraFacing.BACK) {
                    break;
                }
                cameraId++;
            }

            if (cameraId == cameraIds.length) {
                cameraId = 0;
            }
        }

        CameraInfo cameraInfo = cameraKit.getCameraInfo(cameraIds[0]);
        // 相机创建和相机运行时的回调
        CameraStateCallbackImpl cameraStateCallback = new CameraStateCallbackImpl(surfaceOps);
        if (cameraStateCallback == null) {
        }
        // 执行回调的EventHandler
        EventHandler eventHandler = new EventHandler(EventRunner.create("CameraCb"));
        if (eventHandler == null) {
        }
        //创建相机对象
        cameraKit.createCamera(cameraIds[0], cameraStateCallback, eventHandler);
        if (cameraKit == null) {
            return null;
        }
        return new OpenCamera(cameraIds[0], cameraKit, cameraStateCallback.getCamera(),CameraFacing.values()[cameraInfo.getFacingType()], 0);
    }

}
